/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManagerUser.java
 *
 * Created on Jul 25, 2011, 4:14:21 PM
 */
package admin;

import generalCode.Connectionsql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Hoai An
 */
public class ManagerUserForm extends javax.swing.JFrame {

    private ArrayList<UserDTO> listUser = new ArrayList<UserDTO>();
    Vector<String> columnNames;

    {
        columnNames = new Vector<String>();
        columnNames.add("Id");
        columnNames.add("User Name");
        columnNames.add("Password");
        columnNames.add("Level");
    }
    private boolean isUpdate = false;
    private boolean isChange = false;
    private boolean isReset = false;

    /** Creates new form ManagerUser */
    public ManagerUserForm() {
        initComponents();
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        initData();
        this.setTitle("Management users");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lbUserName = new javax.swing.JLabel();
        lbPassword = new javax.swing.JLabel();
        lbLevel = new javax.swing.JLabel();
        lbID = new javax.swing.JLabel();
        btAdd = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();
        btReset = new javax.swing.JButton();
        tfID = new javax.swing.JTextField();
        tfUserName = new javax.swing.JTextField();
        tfLevel = new javax.swing.JTextField();
        tfPassword = new javax.swing.JPasswordField();
        btChangePass = new javax.swing.JButton();
        btResetPass = new javax.swing.JButton();
        pnBottom = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbSetUser = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        cbxSeach = new javax.swing.JComboBox();
        tfSeach = new javax.swing.JTextField();
        btSeach = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "User Information", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
        jPanel1.setLayout(null);

        lbUserName.setText("User Name:");
        jPanel1.add(lbUserName);
        lbUserName.setBounds(70, 70, 80, 20);

        lbPassword.setText("Password: ");
        jPanel1.add(lbPassword);
        lbPassword.setBounds(80, 100, 80, 20);

        lbLevel.setText("Level:");
        jPanel1.add(lbLevel);
        lbLevel.setBounds(90, 130, 50, 20);

        lbID.setText("ID:");
        jPanel1.add(lbID);
        lbID.setBounds(110, 40, 50, 14);

        btAdd.setText("Add");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });
        jPanel1.add(btAdd);
        btAdd.setBounds(170, 160, 90, 23);

        btDelete.setText("Delete");
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteActionPerformed(evt);
            }
        });
        jPanel1.add(btDelete);
        btDelete.setBounds(270, 160, 70, 23);

        btReset.setText("Reset Form");
        btReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btResetActionPerformed(evt);
            }
        });
        jPanel1.add(btReset);
        btReset.setBounds(350, 190, 130, 23);

        tfID.setEditable(false);
        jPanel1.add(tfID);
        tfID.setBounds(200, 40, 240, 20);

        tfUserName.setEditable(false);
        tfUserName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfUserNameActionPerformed(evt);
            }
        });
        jPanel1.add(tfUserName);
        tfUserName.setBounds(200, 70, 240, 20);
        jPanel1.add(tfLevel);
        tfLevel.setBounds(200, 130, 240, 20);

        tfPassword.setEditable(false);
        jPanel1.add(tfPassword);
        tfPassword.setBounds(200, 100, 240, 20);

        btChangePass.setText("Change Password");
        btChangePass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btChangePassActionPerformed(evt);
            }
        });
        jPanel1.add(btChangePass);
        btChangePass.setBounds(170, 190, 170, 23);

        btResetPass.setText("Reset Password");
        btResetPass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btResetPassActionPerformed(evt);
            }
        });
        jPanel1.add(btResetPass);
        btResetPass.setBounds(350, 160, 130, 23);

        tbSetUser.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "ID", "UserName", "Password", "Level"
            }
        ));
        tbSetUser.setColumnSelectionAllowed(true);
        tbSetUser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbSetUserMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbSetUser);
        tbSetUser.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jLabel1.setText("Seach with:");

        cbxSeach.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "      ID", "UserName" }));

        btSeach.setText("Seach");
        btSeach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSeachActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnBottomLayout = new javax.swing.GroupLayout(pnBottom);
        pnBottom.setLayout(pnBottomLayout);
        pnBottomLayout.setHorizontalGroup(
            pnBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnBottomLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 707, Short.MAX_VALUE)
                    .addGroup(pnBottomLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(38, 38, 38)
                        .addComponent(cbxSeach, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addComponent(tfSeach, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(40, 40, 40)
                        .addComponent(btSeach)))
                .addContainerGap())
        );
        pnBottomLayout.setVerticalGroup(
            pnBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnBottomLayout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addGroup(pnBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbxSeach, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfSeach, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSeach)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 707, Short.MAX_VALUE)
                .addGap(10, 10, 10))
            .addComponent(pnBottom, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnBottom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteActionPerformed
        String id = this.tfID.getText();
        int response = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.YES_OPTION) {
            deleteUser(id);
        }
    }//GEN-LAST:event_btDeleteActionPerformed

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        String id = this.tfID.getText();
        String level = this.tfLevel.getText();
        if (!isUpdate) {
            AddNewUser addNewUser = new AddNewUser();
            this.setVisible(false);
        } else if (!(level.equals("2") || level.equals("3") || level.equals("4"))) {
            JOptionPane.showMessageDialog(this, "You only upgrade User to: Manager with Level = 2, Deparment Head with Level = 3 and Employee with Level = 4! Please try again!");
        } else {
            updateUser(level, id);
            this.resetForm();
            this.isUpdate = false;
            this.btAdd.setText("Add");
        }
    }//GEN-LAST:event_btAddActionPerformed

            private void tbSetUserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbSetUserMouseClicked
                isUpdate = true;
                isChange = true;
                isReset = true;
                showInfo();
            }//GEN-LAST:event_tbSetUserMouseClicked

            private void btChangePassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btChangePassActionPerformed
                if (!isChange) {
                    JOptionPane.showMessageDialog(this, "Please! Choose User for update password!");
                } else {
                    ChangePasswordForm cpw = new ChangePasswordForm(this, true);
                    changePass(cpw.pass);

                }
            }//GEN-LAST:event_btChangePassActionPerformed

            private void btResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btResetActionPerformed
                resetForm();
}//GEN-LAST:event_btResetActionPerformed

            private void tfUserNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfUserNameActionPerformed
                // TODO add your handling code here:
}//GEN-LAST:event_tfUserNameActionPerformed

            private void btResetPassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btResetPassActionPerformed
                String id = this.tfID.getText();
                resetPass(id);
            }//GEN-LAST:event_btResetPassActionPerformed

            private void btSeachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSeachActionPerformed
                String inputSeach = this.tfSeach.getText();
                int isSelected = this.cbxSeach.getSelectedIndex();
                if (inputSeach.equals("")) {
                    JOptionPane.showMessageDialog(this, "Input seacch is not blank! Please try again!");
                } else {
                    Seach(inputSeach, isSelected);
                }
}//GEN-LAST:event_btSeachActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btChangePass;
    private javax.swing.JButton btDelete;
    private javax.swing.JButton btReset;
    private javax.swing.JButton btResetPass;
    private javax.swing.JButton btSeach;
    private javax.swing.JComboBox cbxSeach;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbID;
    private javax.swing.JLabel lbLevel;
    private javax.swing.JLabel lbPassword;
    private javax.swing.JLabel lbUserName;
    private javax.swing.JPanel pnBottom;
    public static javax.swing.JTable tbSetUser;
    private javax.swing.JTextField tfID;
    private javax.swing.JTextField tfLevel;
    private javax.swing.JPasswordField tfPassword;
    private javax.swing.JTextField tfSeach;
    private javax.swing.JTextField tfUserName;
    // End of variables declaration//GEN-END:variables

    private void deleteUser(String id) {
        int idAd = Integer.valueOf(id);
        if (idAd == 1) {
            JOptionPane.showMessageDialog(this, "You can't delete Admin!", "Warning", JOptionPane.WARNING_MESSAGE);
        } else {
            try {
                String sql = "delete users where userid=?;";
                Object[] arr = new Object[]{id};
                Connectionsql conn = Connectionsql.newInstance();
                if (conn.updateWithParam(sql, arr)) {
                    JOptionPane.showMessageDialog(this, "Delete user successfully!");
                    initData();
                    conn.closeConn();
                }
            } catch (SQLException ex) {
                Logger.getLogger(ManagerUserForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void updateUser(String level, String id) {
        String idAdmin = this.tfID.getText();
        int idAd = Integer.valueOf(idAdmin);
        int lv = Integer.valueOf(level);
        if (idAd == 1) {
            JOptionPane.showMessageDialog(this, "You can't update Admin!", "Warning", JOptionPane.WARNING_MESSAGE);
        } else {
            try {
                Connectionsql db = Connectionsql.newInstance();
                String sql = "update users set level=? where userid=?;";
                Object[] arr = new Object[]{lv, id};
                if (db.updateWithParam(sql, arr)) {
                    JOptionPane.showMessageDialog(this, "Update User successfully!");
                    initData();
                }
                db.closeConn();
            } catch (SQLException ex) {
                Logger.getLogger(ManagerUserForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void resetForm() {
        this.tfID.setText("");
        this.tfUserName.setText("");
        this.tfPassword.setText("");
        this.tfLevel.setText("");
        this.btAdd.setText("Add");
        isUpdate = false;
    }

    public void initData(){
        initTable(null);
    }
    public void initTable(String sql) {
        try {
            listUser = new ArrayList<UserDTO>();
            this.tbSetUser.removeAll();
            //load db
            Connectionsql db = Connectionsql.newInstance();
            if (sql == null) {
                sql = "select * from users order by userid";
            }
                ResultSet rs = db.query(sql);
                while (rs.next()) {
                    listUser.add(new UserDTO(rs.getInt("userid"), rs.getString("username"),
                            rs.getString("password"), rs.getInt("level")));
                }
                db.closeConn();
                //show table
                Vector<Vector<String>> data = new Vector<Vector<String>>();
                for (int i = 0; i < listUser.size(); i++) {
                    Vector<String> v = new Vector<String>();
                    v.add(listUser.get(i).getId() + "");
                    v.add(listUser.get(i).getUserName());
                    v.add(listUser.get(i).getPassword());
                    v.add(listUser.get(i).getLevel() + "");
                    data.add(v);

                }
                tbSetUser.setModel(new DefaultTableModel(data, columnNames));
            
        } catch (SQLException ex) {
            Logger.getLogger(ManagerUserForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private boolean validateInput() {
        if (tfUserName.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in UserName!");
            return false;
        } else if (tfPassword.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in Password!");
            return false;
        } else if (tfLevel.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in Level!");
        }
        return true;
    }

    private void showInfo() {
        this.btAdd.setText("Update");
        int selectedRow = -1;
        selectedRow = tbSetUser.getSelectedRow();
        if (selectedRow != -1) {
            tfID.setText(listUser.get(selectedRow).getId() + "");
            tfUserName.setText(listUser.get(selectedRow).getUserName());
            tfPassword.setText(listUser.get(selectedRow).getPassword());
            tfLevel.setText(listUser.get(selectedRow).getLevel() + "");
        }
    }

    private void resetPass(String id) {
        if (!isReset) {
            JOptionPane.showMessageDialog(this, "Please! Choose User for update!");
        } else {
            Connectionsql db = Connectionsql.newInstance();
            try {
                String sql = "update users set password=? where Userid=?";
                Object[] arr = new Object[]{123456, id};
                System.out.println(sql);
                if (db.updateWithParam(sql, arr)) {
                    JOptionPane.showMessageDialog(this, "Reset password successfully!");
                    initData();
                }
                db.closeConn();


            } catch (SQLException ex) {
                Logger.getLogger(ManagerUserForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    void changePass(String pass) {
        Connectionsql db = Connectionsql.newInstance();
        String id = this.tfID.getText();
        try {
            String sql = "update users set password=? where userid=?";
            Object[] arr = new Object[]{pass, id};
            if (db.updateWithParam(sql, arr)) {
                JOptionPane.showMessageDialog(this, "Change password successfully!");
                this.dispose();
                ManagerUserForm manage = new ManagerUserForm();
                manage.initData();
            }
            db.closeConn();


        } catch (SQLException ex) {
            Logger.getLogger(ManagerUserForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void Seach(String inputSeach, int isSelected) {
        String sql = "";
        if (isSelected == 0) {
            sql = "select * from Users where userid like " + inputSeach + " order by userid";
        } else if (isSelected == 1) {
            sql = sql = "select * from Users where username like '%" + inputSeach + "%' order by userid";
        }
        initTable(sql);
    }
}